package com.cyc.basic.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class MD5Util {
    private static final String[] hexDigits = new String[]{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
    private static MessageDigest md5Digest = null;

    static {
        try {
            md5Digest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException var1) {
            throw new RuntimeException("MD5 not supported", var1);
        }
    }

    public MD5Util() {
    }

    public static String byteArrayToString(byte[] bytes) {
        StringBuilder builder = new StringBuilder();
        byte[] var5 = bytes;
        int var4 = bytes.length;

        for(int var3 = 0; var3 < var4; ++var3) {
            byte b = var5[var3];
            builder.append(byteToHexString(b));
        }

        return builder.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (b < 0) {
            n = b + 256;
        }

        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin) {
        return origin != null && origin.trim().length() != 0 ? byteArrayToString(computeMd5(origin)) : origin;
    }

    public static String MD5EncodeWithUtf8(String origin) {
        return origin != null && origin.trim().length() != 0 ? byteArrayToString(computeMd5WithUtf8(origin)) : origin;
    }

    public static byte[] computeMd5(String k) {
        MessageDigest md5;
        try {
            md5 = (MessageDigest)md5Digest.clone();
        } catch (CloneNotSupportedException var3) {
            throw new RuntimeException("clone of MD5 not supported", var3);
        }

        md5.update(k.getBytes());
        return md5.digest();
    }

    public static byte[] computeMd5WithUtf8(String k) {
        MessageDigest md5;
        try {
            md5 = (MessageDigest)md5Digest.clone();
        } catch (CloneNotSupportedException var4) {
            throw new RuntimeException("clone of MD5 not supported", var4);
        }

        try {
            md5.update(k.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException var3) {
            throw new RuntimeException("encding utf8 fail", var3);
        }

        return md5.digest();
    }
}